// pages/updateNote/updateNote.js
Page({
  data: {
    noteDetail: null,
    title:"",
    areaMap: ["日常生活", "学术", "人际交往"],
    areaID: 0,
    tag:"",
    text:"",
    imageUrls: [],   // 服务器返回的图片URL
    images: [],      // 新上传的临时图片路径
    imageCount: 0    // 总图片数量
  },

  onLoad(options) {
    const notenum = options.notenum;
    this.loadNoteDetail(notenum);
  },

  // 加载笔记数据
  loadNoteDetail(notenum) {
    const that = this;
    const token = wx.getStorageSync('token');
    wx.request({
      url: `http://localhost:8848/Note/${notenum}`,
      header: {
        'Authorization': `Bearer ${token}`
      },
      success: res => {
        console.log('当前 Token:', wx.getStorageSync('token'));
        console.log('[接口响应]', res.data);
        if (res.statusCode === 200) {
          const note = res.data;
          // 处理图片
          const imageUrls = note.img ? note.img.split(',') : [];
          this.setData({
            noteDetail: note,
            title: note.title,
            text: note.text,
            tag: note.tag,
            areaID: note.areaID, 
            imageUrls: imageUrls,
            imageCount: imageUrls.length
          });
        }
      }
    });
  },

  handleTitleInput(e) {
    this.setData({
        title: e.detail.value
    });
  },

  handleCategoryChange(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value);
    this.setData({
        areaID: e.detail.value
    });
  },

  handleTagInput(e) {
    this.setData({
        tag: e.detail.value
    });
  },
  
  handleTextareaInput(e) {
    this.setData({
        text: e.detail.value
    });
  },

  chooseImage() {
    const that = this;
    wx.chooseImage({
        count: 4 - that.data.imageCount,
        success(res) {
          console.log('选择的图片临时路径:', res.tempFilePaths);
            that.setData({
                images: that.data.images.concat(res.tempFilePaths),
                imageCount: that.data.imageCount + res.tempFilePaths.length
            });
        },
        fail(err) {
            console.error('选择图片失败:', err);
        }
    });
  },

  // 提交更新
  confirm() {
    const that = this;
    console.log("[修改后]",that.data)
    const { title, 
      tag, 
      text, 
      imageUrls, 
      images = [], // 防止undefined
      noteDetail  } = this.data;
    console.log("[检查]",this.data)

    if (!title || !text) {
      wx.showToast({ title: '标题和内容不能为空', icon: 'none' });
      return;
    }

    // 合并新旧图片URL
    const allImages = imageUrls.concat(images.map(img => img.url));

    wx.request({
      url: 'http://localhost:8848/Note/update',
      method: 'PUT',
      header: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + wx.getStorageSync('token')
      },
      data: {
        userID: noteDetail.userID,
        notenum: noteDetail.notenum,
        title: title,
        tag: tag,
        text: text,
        img: allImages.join(','), // 合并后的图片URL
        areaID: noteDetail.areaID
      },
      success(res) {
        if (res.statusCode === 200) {
          const noteId = noteDetail.notenum;
          console.log('用于上传的 notenum:', noteId);
          // 图片上传逻辑
          let uploadPromises = images.map(image => {
            console.log('上传文件路径:', image);
            return new Promise((resolve, reject) => {
                wx.uploadFile({
                    url: 'http://localhost:8848/Note/uploadImage',
                    filePath: image,
                    name: 'file',
                    formData: { noteId: noteId }, 
                    header: {
                        // 去掉 Content-Type 设置，使用默认的 multipart/form-data
                        'Authorization': 'Bearer ' + wx.getStorageSync('token')
                    },
                    success(res) {
                        console.log('上传文件响应:', res);
                        if (res.statusCode === 200) resolve();
                        else {
                            console.error('上传失败，状态码:', res.statusCode, '响应数据:', res.data);
                            reject(new Error('上传失败'));
                        }
                    },
                    
                    fail: (err) => {
                        console.error('上传失败，错误信息:', err);
                        reject(err);
                    }
                });
            });
        });

        

          wx.showToast({ title: '更新成功', icon: 'success' });
          setTimeout(() => wx.navigateBack(), 1500);
        }
      }
    });
  },

  goBack(){
    wx.navigateBack({
      delete:1
    })
  }
});